<template>
  <div class="material-management">
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="物料名称">
          <el-input
              v-model="searchForm.name"
              placeholder="输入物料名称"
              clearable
              @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="物料类别">
          <el-select
              v-model="searchForm.category"
              placeholder="选择类别"
              clearable
          >
            <el-option
                v-for="item in categoryOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="存放位置">
          <el-input
              v-model="searchForm.location"
              placeholder="输入存放位置"
              clearable
              @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="生产厂家">
          <el-input
              v-model="searchForm.manufacturer"
              placeholder="输入生产厂家"
              clearable
              @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="action-buttons">
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>新增物料
      </el-button>
      <el-button type="success" @click="handleExport">
        <el-icon><Download /></el-icon>导出数据
      </el-button>
    </div>

    <!-- 表格区域 -->
    <div class="table-container">
      <el-table
          :data="tableData"
          border
          style="width: 100%"
          v-loading="loading"
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="物料名称" width="180" sortable />
        <el-table-column prop="category" label="类别" width="120">
          <template #default="{ row }">
            <el-tag>{{ row.category }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="quantity" label="库存数量" width="120" sortable>
          <template #default="{ row }">
            <span :class="{ 'low-stock': row.quantity < row.minStock }">
              {{ row.quantity }}
              <el-icon v-if="row.quantity < row.minStock" color="red">
                <Warning />
              </el-icon>
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="location" label="存放位置" width="180" />
        <el-table-column prop="manufacturer" label="生产厂家" width="200" />
        <el-table-column prop="lastUpdate" label="最后更新" width="180" sortable />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button
                size="small"
                type="danger"
                @click="handleDelete(row)"
            >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="50%"
    >
      <el-form
          :model="formData"
          :rules="formRules"
          ref="formRef"
          label-width="120px"
      >
        <el-form-item label="物料名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入物料名称" />
        </el-form-item>
        <el-form-item label="物料类别" prop="category">
          <el-select
              v-model="formData.category"
              placeholder="请选择物料类别"
              style="width: 100%"
          >
            <el-option
                v-for="item in categoryOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="库存数量" prop="quantity">
          <el-input-number
              v-model="formData.quantity"
              :min="0"
              :step="1"
              style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="最低库存" prop="minStock">
          <el-input-number
              v-model="formData.minStock"
              :min="0"
              :step="1"
              style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="存放位置" prop="location">
          <el-input v-model="formData.location" placeholder="请输入存放位置" />
        </el-form-item>
        <el-form-item label="生产厂家" prop="manufacturer">
          <el-input v-model="formData.manufacturer" placeholder="请输入生产厂家" />
        </el-form-item>
        <el-form-item label="规格型号" prop="specification">
          <el-input v-model="formData.specification" placeholder="请输入规格型号" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
              v-model="formData.remark"
              type="textarea"
              :rows="2"
              placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Download, Warning } from '@element-plus/icons-vue'

// 搜索表单
const searchForm = ref({
  name: '',
  category: '',
  location: '',
  manufacturer: ''
})

// 类别选项
const categoryOptions = ref([
  { value: 'raw', label: '原材料' },
  { value: 'semi', label: '半成品' },
  { value: 'finished', label: '成品' },
  { value: 'tool', label: '工具' },
  { value: 'spare', label: '备件' },
  { value: 'chemical', label: '化学品' }
])

// 表格数据
const tableData = ref([])

// 加载状态
const loading = ref(false)

// 分页信息
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('新增物料')
const formData = ref({
  id: '',
  name: '',
  category: '',
  quantity: 0,
  minStock: 10,
  location: '',
  manufacturer: '',
  specification: '',
  remark: ''
})

// 表单验证规则
const formRules = ref({
  name: [{ required: true, message: '请输入物料名称', trigger: 'blur' }],
  category: [{ required: true, message: '请选择物料类别', trigger: 'change' }],
  quantity: [{ required: true, message: '请输入库存数量', trigger: 'blur' }],
  minStock: [{ required: true, message: '请输入最低库存', trigger: 'blur' }],
  location: [{ required: true, message: '请输入存放位置', trigger: 'blur' }]
})

// 表单引用
const formRef = ref(null)

// 选中的行
const selectedRows = ref([])

// 获取物料列表
const fetchMaterialList = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))

    // 模拟数据
    const mockData = Array.from({ length: 45 }, (_, i) => ({
      id: i + 1,
      name: `物料-${i + 1}`,
      category: categoryOptions.value[i % categoryOptions.value.length].label,
      quantity: Math.floor(Math.random() * 1000),
      minStock: 50,
      location: ['仓库A', '仓库B', '仓库C'][i % 3] + `-${(i % 20) + 1}区`,
      manufacturer: ['厂商A', '厂商B', '厂商C', '厂商D'][i % 4],
      specification: `SPEC-${i % 10}`,
      lastUpdate: `2023-${String((i % 12) + 1).padStart(2, '0')}-${String((i % 28) + 1).padStart(2, '0')}`,
      remark: i % 4 === 0 ? '需要定期检查' : ''
    }))

    // 应用筛选条件
    let filteredData = [...mockData]
    if (searchForm.value.name) {
      filteredData = filteredData.filter(item =>
          item.name.includes(searchForm.value.name)
      )
    }
    if (searchForm.value.category) {
      filteredData = filteredData.filter(item =>
          item.category === searchForm.value.category
      )
    }
    if (searchForm.value.location) {
      filteredData = filteredData.filter(item =>
          item.location.includes(searchForm.value.location)
      )
    }
    if (searchForm.value.manufacturer) {
      filteredData = filteredData.filter(item =>
          item.manufacturer.includes(searchForm.value.manufacturer)
      )
    }

    // 更新分页信息
    pagination.value.total = filteredData.length

    // 分页处理
    const start = (pagination.value.currentPage - 1) * pagination.value.pageSize
    const end = start + pagination.value.pageSize
    tableData.value = filteredData.slice(start, end)
  } catch (error) {
    ElMessage.error('获取物料列表失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

// 处理查询
const handleSearch = () => {
  pagination.value.currentPage = 1
  fetchMaterialList()
}

// 重置查询
const resetSearch = () => {
  searchForm.value = {
    name: '',
    category: '',
    location: '',
    manufacturer: ''
  }
  handleSearch()
}

// 处理新增
const handleAdd = () => {
  dialogTitle.value = '新增物料'
  formData.value = {
    id: '',
    name: '',
    category: '',
    quantity: 0,
    minStock: 10,
    location: '',
    manufacturer: '',
    specification: '',
    remark: ''
  }
  dialogVisible.value = true
}

// 处理编辑
const handleEdit = (row) => {
  dialogTitle.value = '编辑物料'
  formData.value = { ...row }
  dialogVisible.value = true
}

// 处理删除
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除此物料吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 实际项目中调用API删除
    ElMessage.success('删除成功')
    fetchMaterialList()
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 处理导出
const handleExport = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一条数据导出')
    return
  }
  ElMessage.success('导出成功（模拟）')
  // 实际项目中这里应该调用导出API
}

// 处理选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 提交表单
const submitForm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      // 模拟API调用
      setTimeout(() => {
        ElMessage.success(dialogTitle.value + '成功')
        dialogVisible.value = false
        fetchMaterialList()
      }, 500)
    } else {
      return false
    }
  })
}

// 处理分页大小变化
const handleSizeChange = (val) => {
  pagination.value.pageSize = val
  fetchMaterialList()
}

// 处理当前页变化
const handleCurrentChange = (val) => {
  pagination.value.currentPage = val
  fetchMaterialList()
}

// 计算低库存样式
const lowStockClass = computed(() => {
  return (quantity, minStock) => {
    return quantity < minStock ? 'low-stock' : ''
  }
})

// 初始化加载数据
onMounted(() => {
  fetchMaterialList()
})
</script>

<style scoped>
.material-management {
  padding: 20px;
}

.search-container {
  background-color: #f5f7fa;
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 4px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
}

.action-buttons {
  margin-bottom: 20px;
}

.table-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.low-stock {
  color: #f56c6c;
  font-weight: bold;
}
</style>